package com.jspica.app.messagespam;

import java.sql.SQLException;
import java.util.*;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.*;
import android.database.Cursor;
import android.net.*;
import android.os.Bundle;
import android.telephony.*;
import android.util.*;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.google.ads.*;
import com.jspica.app.messagespam.R;
import com.jspica.app.messagespam.Receiver;
import com.jspica.app.messagespam.BlockedListDAO;
import com.jspica.app.messagespam.MyCursorAdapter;

public class MessageSpam extends Activity {

	private ListView blockedList;
	private Cursor cursor;
	private Spinner sortNameList;
	private Button btnDeleteAll;
	//private Button btnRestore;
	private CheckBox chkAll;

	String sortField = "time";

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		

		

		setContentView(R.layout.blockedlist);
	

		
		
		
		setTitle(getResources().getString(R.string.app_name) + " - " +
			getResources().getString(R.string.blocked_msg));
				
		Receiver.block_cnt = 0; /* 차단수 초기화 */

		initiateMembers();
		setEventHandlers();
		registerForContextMenu(blockedList);
		
		
		
		
		
		/* 광고 */
		AdView adView = new AdView(this, AdSize.BANNER, "a14e0339927d0c2");
		LinearLayout layout = (LinearLayout)findViewById(R.id.ad);
		layout.addView(adView);
		adView.loadAd(new AdRequest());		
		
		
		
		
	}

	/* 길게 누르면 출력되는 메뉴. 다음 버전에서 반영 
	@Override
	public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
		menu.add(0, 0, 0, "delete");
	}
	*/

	@Override
	protected void onResume() {
		super.onResume();
		populateList();
		//setEventHandlers();
	}

	/**
	 * 검색조건에 맞는 신용카드 사용 내역을 조회하여 어뎁터로 할당한다.
	 * @throws SQLException 
	 */
	private void populateList() {

		releaseResources();

		ListAdapter adapter;
		BlockedListDAO manager = new BlockedListDAO(getBaseContext());
		try {
			cursor = manager.getListAll();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		startManagingCursor(cursor);

		adapter = new MyCursorAdapter(this, R.layout.blockedrow, cursor, BlockedListDAO.allFields, 
				new int[] {R.id._id, R.id.sms_body, R.id.sender, R.id.time});

		blockedList.setAdapter(adapter);
		
		Log.e("populateList", "@@@@@@@@@@@@ : " + blockedList.getChildCount());
		
		manager.close();
		manager = null;

	}

	private void releaseResources() {
		if (cursor != null) {
			cursor.close();
			cursor = null;
		}
	}

	/**
	 * 레이어웃의 요소들을 가져와 멤버변후에 바인딩 시킨다.
	 */
	private void initiateMembers() {
		blockedList = (ListView)findViewById(R.id.blockedList);
		btnDeleteAll = (Button)findViewById(R.id.deleteAll);
		//btnRestore = (Button)findViewById(R.id.restore);
		chkAll = (CheckBox)findViewById(R.id.checkAll);
	}

	/* 리스트 길게 클릭시 이벤트 처리.. 일단 막어둠. 다음버전에서 반영.
	@Override
	public boolean onContextItemSelected(MenuItem selectedContextItem) {
		AdapterContextMenuInfo selectedMenuInfo = (AdapterContextMenuInfo)selectedContextItem.getMenuInfo();
		final Cursor cursor = (Cursor)blockedList.getItemAtPosition(selectedMenuInfo.position);

		if (selectedContextItem.getItemId() == 0) { // 삭제하기
			BlockedListDAO smsListDao = new BlockedListDAO(getBaseContext());
			smsListDao.deleteRow(cursor.getInt(cursor.getColumnIndex("_id")));
			smsListDao.close();
			populateList();
		}
		return true;
	}
	*/

	/**
	 * 버튼들에 대한 클릭 이벤트 리스너를 등록한다.
	 */
	private void setEventHandlers() {
		btnDeleteAll.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new AlertDialog.Builder(MessageSpam.this)
				.setTitle(getResources().getString(R.string.confirm))
				.setMessage(getResources().getString(R.string.do_delete))
				.setCancelable(false) // Back버튼 작동안하도록.
				.setPositiveButton(getResources().getString(R.string.yes),
					new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
												
						BlockedListDAO smsListDao = new BlockedListDAO(getBaseContext());
						//smsListDao.deleteAll();
						
						CheckBox cb = null;
						
						Log.e("Delbutton", "@@@@@@@@@@@@ : " + blockedList.getChildCount());
						for (int i = 0; i < blockedList.getChildCount(); i++) {
							cb = (CheckBox)blockedList.getChildAt(i).findViewById(R.id.check);
							
							if (cb.isChecked()) {
								TextView view = (TextView)blockedList.getChildAt(i).findViewById(R.id._id);
								//Log.e("STring@@@@@@@@@@@@@@", (String)view.getText());
								
								smsListDao.deleteRow(Integer.parseInt((String)view.getText()));
							}
						}
									
						//adapter.getItem(position);
						
						//Log.e("@@@@2count@@@@@@@@@", "len: " + adapter.getCount());
						
						smsListDao.close();
						populateList();
						
						
						
					}			
				})
				.setNegativeButton(getResources().getString(R.string.no), null)
				.show();
			}
		});
		
		/*
		btnRestore.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				BlockedListDAO smsListDao = new BlockedListDAO(getBaseContext());
				//smsListDao.deleteAll();
				
				CheckBox cb = null;
				
				for (int i = 0; i < blockedList.getChildCount(); i++) {
					cb = (CheckBox)blockedList.getChildAt(i).findViewById(R.id.check);
					
					if (cb.isChecked()) {
						// SMS 복구 
						TextView sender  = (TextView)blockedList.getChildAt(i).findViewById(R.id.sender);
						TextView time  = (TextView)blockedList.getChildAt(i).findViewById(R.id.time);
						TextView body  = (TextView)blockedList.getChildAt(i).findViewById(R.id.sms_body);
						
						
						ContentValues val = new ContentValues();
						//val.put("address", (String)sender.getText());
						val.put("address", "5556");
						//val.put("date", (String)time.getText());
						Date date = new Date();
						//val.put("date", date.getTime());
						val.put("date", new Date(java.lang.System.currentTimeMillis()).toString());
						val.put("read", 1);
						val.put("status", -1);
						val.put("type", 2);
						//val.put("body", (String)body.getText());
						val.put("body", "restore");
						
						Uri ok = getContentResolver().insert(Uri.parse("content://sms"), val);	
						
						if (ok != null) {
							Log.e("@@@@@@@@@@@","OK~~~" + (String)sender.getText() +date.getTime() + (String)body.getText() );
						} else {
							Log.e("@@@@@@@@@@@","NO~~~");
						}
						
						SmsManager sms = SmsManager.getDefault();
						sms.sendTextMessage("01092123969", "01028271022", "hello", null, null);
						
						// 내부DB에서 SMS 삭제 
						TextView view = (TextView)blockedList.getChildAt(i).findViewById(R.id._id);
						//Log.e("STring@@@@@@@@@@@@@@", (String)view.getText());
						
						//smsListDao.deleteRow(Integer.parseInt((String)view.getText()));
					}
				}
							
				//adapter.getItem(position);
				
				//Log.e("@@@@2count@@@@@@@@@", "len: " + adapter.getCount());
				
				smsListDao.close();
				populateList();
			}
		});
		*/
			
		
		chkAll.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				
				CheckBox cb = null;
				
				Log.e("Check", "@@@@@@@@@@@@ : " + blockedList.getChildCount());
				
				for (int i = 0; i < blockedList.getChildCount(); i++) {
					cb = (CheckBox)blockedList.getChildAt(i).findViewById(R.id.check);
					cb.setChecked(isChecked);
				}
			}
		});
	}
	
	
	/* 메뉴 버튼 - 옵션창 출력 */
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);

		MenuItem m = menu.add(0, 0x03, 0, R.string.settings);
		m.setIcon(android.R.drawable.ic_menu_preferences);
						
		return result;
	}

	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		boolean result = super.onOptionsItemSelected(item);
		Intent intent = null;

		switch (item.getItemId()) {
		case 0x03: {
			try {
				intent = new Intent(this, Preferences.class);
				startActivity(intent);
			} catch (ActivityNotFoundException e) {
			}
		}
			break;
		}

		return result;
	}
	
}
